package com.irwin.skin;


import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.ViewGroup;

import com.irwin.skin.ISkinnable;
import com.irwin.skin.SkinManager;
import com.irwin.skin.SkinUtils;
import com.irwin.skin.resources.BaseResources;

public abstract class BaseActivity extends FragmentActivity implements ISkinnable {

    private View mContentView;

    private int mLayoutId = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerSkinCallback();
    }


    protected void registerSkinCallback() {
        SkinManager.getInstance().register(this);
    }

    @Override
    public void setContentView(int layoutResID) {
        mLayoutId = layoutResID;
        View contentView = ((BaseResources) getResources()).getView(this, layoutResID);
        setContentView(contentView);
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        mContentView = view;
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        super.setContentView(view, params);
        mContentView = view;
    }


    @Override
    public int getLayoutRes() {
        if (mLayoutId <= 0) {
            throw new IllegalStateException("Layout id should be provided ether by setContentView(int layoutId) or override getLayoutRes() method");
        }
        return mLayoutId;
    }

    @Override
    public void onSkinChanged(BaseResources resources) {
        View v = resources.getView(this, getLayoutRes());
        if (SkinUtils.isSameLayout(mContentView, v)) {
            return;
        }
        setContentView(v);
        bindViewData();
    }

    @Override
    public Resources getResources() {
        return getSkinResources();
    }

    public BaseResources getSkinResources() {
        return SkinManager.getInstance().getResources();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SkinManager.getInstance().unregister(this);
    }
}

